package com.wangsd.web.mircomerchant.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wangsd.common.basicbean.Result;
import com.wangsd.web.face.entity.CertFicatesBase;
import com.wangsd.web.face.entity.Micro;
import com.wangsd.web.face.service.CertFicatesBaseService;
import com.wangsd.web.face.service.MicroService;
import com.wangsd.web.mircomerchant.MicroSubmit;
import com.wangsd.web.mircomerchant.service.CertFicatesService;
import com.wangsd.web.mircomerchant.upload.service.UploadService;
import com.wangsd.web.mircomerchant.utils.EncryptionUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author generator
 * @since 2019-09-09
 */
@Api(value = "mircoSubmit", tags = "小微商户进件")
@Controller
@RequestMapping("/face/mircoSubmit")
@Slf4j
public class MircoSubmitController {

    @Autowired
    private UploadService uploadService;

    @Autowired
    private CertFicatesService certFicatesService;

    @Autowired
    private MicroService microService;

    @Autowired
    private CertFicatesBaseService certFicatesBaseService;

    @ApiOperation(value = "获取平台证书序列号", notes = "获取平台证书序列号")
    @RequestMapping(value = "/getCertFicates", method = RequestMethod.POST)
    @ResponseBody
    public Result getCertFicates(@ApiParam(value = "商户号", required = true) @RequestParam String mchId,
                                 @ApiParam(value = "商户密钥", required = true) @RequestParam String apiSecret,
                                 @ApiParam(value = "证书名称", required = true) @RequestParam String certPath,
                                 @ApiParam(value = "apiv3key", required = true) @RequestParam String apiv3key) {
        try {
            JSONObject certFicates = certFicatesService.getCertFicates(mchId, apiSecret);
            if ("SUCCESS".equals(certFicates.get("return_code"))) {
                if ("SUCCESS".equals(certFicates.get("result_code"))) {
                    CertFicatesBase certFicatesBase = new CertFicatesBase();
                    Object certificates = certFicates.get("certificates");
                    String s = JSON.toJSONString(certificates).replace("\\", "");
                    s = s.replaceFirst("\"", "");
                    s = s.substring(0, s.length() - 1);
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    JSONArray dataArray = JSONArray.parseArray(JSON.toJSONString(jsonObject.get("data")));
                    JSONObject dataJsonObject = JSONObject.parseObject(JSON.toJSONString(dataArray.get(0)));
                    JSONObject encryptJsonObject = dataJsonObject.getJSONObject("encrypt_certificate");
                    CertFicatesBase concat_phone = certFicatesBaseService.getOne(new QueryWrapper<CertFicatesBase>().eq("mch_id", mchId));
                    certFicatesBase.setSerialNo(dataJsonObject.getString("serial_no"));
                    certFicatesBase.setNonce(encryptJsonObject.getString("nonce"));
                    certFicatesBase.setAssociatedData(encryptJsonObject.getString("associated_data"));
                    certFicatesBase.setCipherText(encryptJsonObject.getString("ciphertext"));
                    certFicatesBase.setMchId(mchId);
                    certFicatesBase.setApiSecret(apiSecret);
                    certFicatesBase.setCertPath(certPath);
                    certFicatesBase.setApiv3Key(apiv3key);
                    if (concat_phone == null) {
                        certFicatesBaseService.save(certFicatesBase);
                    } else {
                        certFicatesBase.setId(concat_phone.getId());
                        certFicatesBaseService.updateById(certFicatesBase);
                    }
                    return Result.success(certFicates);
                }
            }
            log.info("接口返回参数\"serial_no\"即为平台证书序列号 {}", certFicates);
            return Result.fail(JSON.toJSONString(certFicates));
        } catch (Exception e) {
            log.error("接口返回参数\"serial_no\"即为平台证书序列号 {}", e);
        }
        return null;
    }

    /**
     * 上传小微商户图片
     *
     * @param multipartFile
     * @return
     */
    @ApiOperation(value = "小微商户进件图片上传", notes = "小微商户进件图片上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query",
                    allowableValues = "身份证人像面,身份证国徽面,门店门口照片,店内环境照片", required = true)
    })
    public Result upload(
            @ApiParam(value = "商户号", required = true) @RequestParam String mchId,
            @ApiParam(value = "手机号", required = true) @RequestParam String contactPhone,
            @ApiParam(value = "类型", required = true) @RequestParam String type,
            @ApiParam(value = "图片", required = true) @RequestParam MultipartFile multipartFile
    ) {
        log.info("图片大小 {}，手机号{},类型{}",
                multipartFile.getSize(), contactPhone, type);
        CertFicatesBase base = certFicatesBaseService.getOne(new QueryWrapper<CertFicatesBase>().eq("mch_id", mchId));
        if (base == null) {
            return Result.fail("请先获取序列号！");
        }
        Micro micro = microService.getOne(new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
        if (micro == null) {
            micro = new Micro();
        }

        micro.setContactPhone(contactPhone);
        String s = uploadService.uploadFile(multipartFile, base.getMchId(), base.getApiSecret(), base.getCertPath());
        if (s.contains("ERROR") || s.contains("error")) {
            return Result.fail(s);
        }
        if ("身份证人像面".equalsIgnoreCase(type)) {
            if (micro.getId() == null) {
                micro.setIdCardCopy(s);
                microService.save(micro);
            } else {
                micro.setIdCardCopy(s);
                microService.update(micro, new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
            }
        } else if ("身份证国徽面".equalsIgnoreCase(type)) {
            if (micro.getId() == null) {
                micro.setIdCardNational(s);
                microService.save(micro);
            } else {
                micro.setIdCardNational(s);
                microService.update(micro, new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
            }
        } else if ("门店门口照片".equalsIgnoreCase(type)) {
            if (micro.getId() == null) {
                micro.setStoreEntrancePic(s);
                microService.save(micro);
            } else {
                micro.setStoreEntrancePic(s);
                microService.update(micro, new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
            }
        } else if ("店内环境照片".equalsIgnoreCase(type)) {
            if (micro.getId() == null) {
                micro.setIndoorPic(s);
                microService.save(micro);
            } else {
                micro.setIndoorPic(s);
                microService.update(micro, new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
            }
        }
        return Result.success(s);
    }


    @ApiOperation(value = "获取加密内容", notes = "获取加密内容")
    @RequestMapping(value = "/rsaEncryptByCert", method = RequestMethod.GET)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query", required = true,
                    allowableValues = "身份证姓名,身份证号码,银行账号,手机号码")
    })
    public Result rsaEncryptByCert(@ApiParam(value = "商户号", required = true) @RequestParam String mchId,
                                   @ApiParam(value = "手机号", required = true) @RequestParam String contactPhone,
                                   @ApiParam(value = "加密内容", required = true) @RequestParam String content,
                                   @ApiParam(value = "类型", required = true) @RequestParam String type) {
        try {
            CertFicatesBase base = certFicatesBaseService.getOne(new QueryWrapper<CertFicatesBase>().eq("mch_id", mchId));
            /**/
            if (base == null) {
                return Result.fail("请先获取序列号！");
            }
            String certStr = certFicatesService.decryptCertSN(base.getAssociatedData(), base.getNonce(), base.getCipherText(), base.getApiv3Key());
            String encrypt = EncryptionUtils.rsaEncryptByCert(content, certStr);
            log.info("加密串:{}", encrypt);
            Micro micro = microService.getOne(new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
            if (micro == null) {
                micro = new Micro();
            }
            if (encrypt.contains("ERROR") || encrypt.contains("error")) {
                return Result.fail(encrypt);
            }

            micro.setContactPhone(contactPhone);
            if ("身份证姓名".equalsIgnoreCase(type)) {
                if (micro.getId() == null) {
                    micro.setIdCardName(encrypt);
                    microService.save(micro);
                } else {
                    micro.setIdCardName(encrypt);
                    microService.update(micro, new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
                }
            } else if ("身份证号码".equalsIgnoreCase(type)) {
                if (micro.getId() == null) {
                    micro.setIdCardNumber(encrypt);
                    microService.save(micro);
                } else {
                    micro.setIdCardNumber(encrypt);
                    microService.update(micro, new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
                }
            } /*else if ("开户名称".equalsIgnoreCase(type)) {
                if (micro.getId() == null) {
                    micro.setAccount_name(encrypt);
                    micro.setContactPhone(concatPhone);
                    microService.save(micro);
                } else {
                    micro.setAccount_name(encrypt);
                    microService.update(micro, new QueryWrapper<Micro>().eq("contact_phone", concatPhone));
                }
            } */ else if ("银行账号".equalsIgnoreCase(type)) {
                if (micro.getId() == null) {
                    micro.setAccountNumber(encrypt);
                    microService.save(micro);
                } else {
                    micro.setAccountNumber(encrypt);
                    microService.update(micro, new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
                }
            } /*else if ("超级管理员姓名".equalsIgnoreCase(type)) {
                if (micro.getId() == null) {
                    micro.setContact(encrypt);
                    micro.setContactPhone(concatPhone);
                    microService.save(micro);
                } else {
                    micro.setContact(encrypt);
                    microService.update(micro, new QueryWrapper<Micro>().eq("contact_phone", concatPhone));
                }
            }*/ else if ("手机号码".equalsIgnoreCase(type)) {
                if (micro.getId() == null) {
                    micro.setSecretContactPhone(encrypt);
                    microService.save(micro);
                } else {
                    micro.setSecretContactPhone(encrypt);
                    microService.update(micro, new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
                }
            }
            return Result.success(encrypt);
        } catch (Exception e) {
            log.error("解密异常啦 {}", e);
            return Result.fail("解密异常啦:" + e.getMessage());
        }
    }


    @ApiOperation(value = "申请入驻", notes = "申请入驻")
    @RequestMapping(value = "/microSubmit", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accountBank", value = "开户银行", dataType = "String", paramType = "query", required = true,
                    allowableValues = "工商银行,交通银行,招商银行,民生银行,中信银行,浦发银行,兴业银行," +
                            "光大银行,广发银行,平安银行,北京银行,华夏银行,农业银行,建设银行,邮政储蓄银行,中国银行," +
                            "宁波银行,其他银行")
    })
    @ResponseBody
    public Result microSubmit(
            @ApiParam(value = "手机号", required = true) @RequestParam String contactPhone,
            @ApiParam(value = "商户号", required = true) @RequestParam String mchId,
            @ApiParam(value = "身份证有效期限 格式：[\"1970-01-01\",\"长期\"]", required = true) @RequestParam String idCardValidTime,
            @ApiParam(value = "门店名称", required = true) @RequestParam String storeName,
            @ApiParam(value = "门店街道名称", required = true) @RequestParam String storeStreet,
            @ApiParam(value = "商户简称", required = true) @RequestParam String merchantShortname,
            @ApiParam(value = "开户银行全称（含支行）") @RequestParam(required = false) String bankName,
            String accountBank) {
        Micro micro = microService.getOne(new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
        CertFicatesBase certFicatesBase = certFicatesBaseService.getOne(new QueryWrapper<CertFicatesBase>().eq("mch_id", mchId));
        if (micro == null) {
            return Result.fail("请先将加密信息或者图片上传");
        }
        if (certFicatesBase.getSerialNo() == null) {
            return Result.fail("序列号未获取");
        }
        if (micro.getIdCardCopy() == null) {
            return Result.fail("身份证人像图片未上传");
        }
        if (micro.getIdCardNational() == null) {
            return Result.fail("身份证国徽图片未上传");
        }
        if (micro.getIdCardName() == null) {
            return Result.fail("身份证名称未加密");
        }
        if (micro.getIdCardNumber() == null) {
            return Result.fail("身份证号码未加密");
        }
        if (micro.getAccountNumber() == null) {
            return Result.fail("银行账号未加密");
        }
        if (micro.getStoreEntrancePic() == null) {
            return Result.fail("门店门口照片");
        }
        if (micro.getIndoorPic() == null) {
            return Result.fail("店内环境照片");
        }
        if (micro.getSecretContactPhone() == null) {
            return Result.fail("手机号码未加密");
        }
        try {
            MicroSubmit microSubmit = new MicroSubmit();
            microSubmit.setMch_id(certFicatesBase.getMchId());
            microSubmit.setVersion("3.0");
            microSubmit.setCert_sn(certFicatesBase.getSerialNo());
            String str = System.currentTimeMillis() + "";
            microSubmit.setBusiness_code(str);
            microSubmit.setId_card_copy(micro.getIdCardCopy());
            microSubmit.setId_card_national(micro.getIdCardNational());
            microSubmit.setId_card_name(micro.getIdCardName());
            microSubmit.setId_card_number(micro.getIdCardNumber());
            microSubmit.setId_card_valid_time(idCardValidTime);
            microSubmit.setAccount_bank(accountBank);
            microSubmit.setBank_address_code("500000");
            microSubmit.setAccount_number(micro.getAccountNumber());
            microSubmit.setStore_name(storeName);
            microSubmit.setStore_address_code("500000");
            microSubmit.setStore_street(storeStreet);
            microSubmit.setStore_entrance_pic(micro.getStoreEntrancePic());
            microSubmit.setIndoor_pic(micro.getIndoorPic());
            microSubmit.setMerchant_shortname(merchantShortname);
            microSubmit.setService_phone(contactPhone);
            microSubmit.setProduct_desc("线下零售");
            microSubmit.setRate("0.6%");
            microSubmit.setBank_name(bankName);
            microSubmit.setContact_phone(micro.getSecretContactPhone());
            JSONObject jsonObject = certFicatesService.microSubmit(microSubmit, certFicatesBase.getApiSecret(), certFicatesBase.getCertPath());

            if ("SUCCESS".equals(jsonObject.get("return_code"))) {
                if ("SUCCESS".equals(jsonObject.get("result_code"))) {
                    micro.setApplymentId(jsonObject.getString("applyment_id"));
                    microService.update(micro, new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
                    return Result.success(jsonObject);
                }
            }
            return Result.fail(JSON.toJSONString(jsonObject));
        } catch (Exception e) {
            log.error("申请入驻 {}", e);
        }
        return null;
    }


    @ApiOperation(value = "查询申请状态", notes = "查询申请状态", httpMethod = "GET")
    @GetMapping(value = "/microGetstate")
    @ResponseBody
    public Result microGetstate(@ApiParam(value = "手机号", required = true) @RequestParam String contactPhone,
                                @ApiParam(value = "商户号", required = true) @RequestParam String mchId) {
        Micro micro = microService.getOne(new QueryWrapper<Micro>().eq("contact_phone", contactPhone));
        CertFicatesBase certFicatesBase = certFicatesBaseService.getOne(new QueryWrapper<CertFicatesBase>().eq("mch_id", mchId));
        if (micro == null) {
            return Result.fail("请先将加密信息或者图片上传");
        }
        try {
            JSONObject microGetstate = certFicatesService.microGetstate(certFicatesBase.getMchId(), certFicatesBase.getApiSecret(), certFicatesBase.getCertPath(), micro.getApplymentId());
            if ("SUCCESS".equals(microGetstate.get("return_code"))) {
                if ("SUCCESS".equals(microGetstate.get("result_code"))) {
                    return Result.success(microGetstate);
                }
            }
            return Result.fail(JSON.toJSONString(microGetstate));
        } catch (Exception e) {
            log.error("查询申请状态 {}", e);
        }
        return null;
    }


}

